//
//  chaxunjinqi.m
//  shuilijuOASystem
//
//  Created by michael on 16/10/18.
//  Copyright © 2016年 czd. All rights reserved.
//

#import "chaxunjinqi.h"
#import "huiyishiTableViewController.h"
#import "ComingworkongController.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OADetailViewController.h"
#import "OADetailDisPatchController.h"
#import "OAUnDoneListCell.h"
#import "PickerChoiceView.h"
#import "TableViewCell.h"
#import "EatViewController.h"
#import "MeetingViewController.h"
#import "MHDatePicker.h"
#import "OAUnDoneListCell.h"
@interface chaxunjinqi ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int currentPage; //当前页
@property (nonatomic,strong)NSMutableArray *mutArray;
@property (strong, nonatomic) MHDatePicker *selectDatePicker;
@property (strong, nonatomic)UIButton * button1;

@end

@implementation chaxunjinqi

- (void)viewDidLoad {
    [super viewDidLoad];

        __weak typeof(self) weakSelf = self;

    self.view.backgroundColor = [UIColor whiteColor];
    _TableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) style:UITableViewStylePlain];
    self.TableView.delegate = self;
    self.TableView.dataSource =self;
    UIImageView *backImageView=[[UIImageView alloc]initWithFrame:self.view.bounds];
       [backImageView setImage:[UIImage imageNamed:@"近期经办背景"]];
self.TableView.backgroundView = backImageView;

    [self.view addSubview:_TableView];
 self.method = @"handDbSearch";
    self.url = exchSearch;
self.title = _string;
//[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"11" object:nil];
    [self.TableView addHeaderWithCallback:^{
        weakSelf.currentPage = 1;

        [weakSelf loadData]; //加载网络数据
    }];
    [self.TableView headerBeginRefreshing];
    
    [self.TableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
             [weakSelf loadMore];
        }else{
        
            [weakSelf.TableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
    
        }
       
    }];
}
- (void)loadData{

    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"db":_db},@{@"condition":_text},@{@"sName":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
           [self.dataArray removeAllObjects];
        }
        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        [self.TableView reloadData];
        [self.TableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
        [self.view makeToast:[NSString stringWithFormat:@"暂时还没有数据哦"]];
        }
    } failure:^(NSError *error) {
     [self.TableView headerEndRefreshing];
        
    }];
    
    

}
#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"db":_db},@{@"sName":userId},@{@"condition":_text},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        self.currentPage++;
                [self.TableView reloadData];

        [self.TableView footerEndRefreshing];
       
    } failure:^(NSError *error) {
         [self.TableView footerEndRefreshing];
    }];
    
}
//
//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * nameElement = [[data elementsForName:@"上一办理人"] objectAtIndex:0];
            GDataXMLElement * stateElement = [[data elementsForName:@"公文状态"] objectAtIndex:0];
            GDataXMLElement * formElement = [[data elementsForName:@"表单"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            GDataXMLElement * yearElement = [[data elementsForName:@"dbpath"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.name = [nameElement stringValue];
            model.state = [stateElement stringValue];
            model.form = [formElement stringValue];
            model.fileId = [fileIdElement stringValue];
            model.year = [yearElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue];
    }
   
     self.title = [NSString stringWithFormat:@"%@(%lu)",_string,self.totalCounts];

    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UnDoneModel * model = self.dataArray[indexPath.row];
    CGFloat  titleFloat  = [OAToolBox sizebyText:model.title font:14 minsWidth:60];
    NSString * desstring = [NSString stringWithFormat:@"%@/%@/%@",model.time,model.state,model.name];
    CGFloat desFloat = [OAToolBox sizebyText:desstring font:14 minsWidth:80];
    return  titleFloat + desFloat + 20;
//return ( KScreenHeight-64)/10;
}




#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
                    cell.backgroundColor=[UIColor clearColor];//关键语句  

    UnDoneModel * model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UnDoneModel * model = self.dataArray[indexPath.row];
          UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

detailViewController * detailVC = (detailViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"detail"];
detailVC.fileId = model.fileId;
if ([_xqmethod isEqualToString:@"toybFwPage"]||[_xqmethod isEqualToString:@"toybSwPage"]) {
    detailVC.type = @"work1";
}
else {
detailVC.type = @"work2";

}




[self.navigationController pushViewController:detailVC animated:YES];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
